package com.tc.controller;

import com.tc.dto.LoginDTO;
import com.tc.service.IAuthService;
import com.tc.vo.CaptchaVO;
import com.tc.vo.LoginVO;
import com.tc.utils.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 认证控制器
 * </p>
 *
 * @author tc
 * @since 2025-07-10
 */
@RestController
@RequestMapping("/auth")
@Api(tags = "认证管理")
public class AuthController {

    @Autowired
    private IAuthService authService;

    @GetMapping("/captcha")
    @ApiOperation("获取验证码")
    public ResultVo<CaptchaVO> getCaptcha() {
        return authService.generateCaptcha();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResultVo<LoginVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        return authService.login(loginDTO);
    }

    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public ResultVo<Void> logout(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        return authService.logout(token);
    }

    @PostMapping("/refresh")
    @ApiOperation("刷新令牌")
    public ResultVo<LoginVO> refreshToken(@RequestParam String refreshToken) {
        return authService.refreshToken(refreshToken);
    }

    /**
     * 从请求中获取令牌
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
